package com.xkcyy.one.ai.common.tool;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import com.xkcyy.one.ai.llm.model.ToolDefinitionFunction;
import com.xkcyy.one.ai.llm.model.ToolDefinitionParameter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * 抽象工具类
 * 
 * @author yuand
 */
@Slf4j
public abstract class AbstractTool implements Tool {
    protected final ToolDefinition definition;
    protected final ObjectMapper objectMapper;

    public AbstractTool(ToolDefinition definition) {
        this.definition = definition;
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public ToolDefinition getDefinition() {
        return definition;
    }

    @Override
    public String execute(String jsonInputParams) {
        if (!validateInput(jsonInputParams)) {
            throw new IllegalArgumentException("Invalid input parameters");
        }
        return executeInternal(jsonInputParams);
    }

    /**
     * 执行工具内部逻辑
     */
    protected abstract  String executeInternal(String inputParams);

    /**
     * 验证输入参数
     */
    @Override
    public boolean validateInput(String inputParams) {
        try {
            JsonNode params = objectMapper.readTree(inputParams);
            ToolDefinitionFunction function = definition.getFunction();
            List<String> requiredParams = function.getParameters().getRequired();

            // 检查必需参数
            for (String param : requiredParams) {
                if (!params.has(param)) {
                    log.error("Missing required parameter: {}", param);
                    return false;
                }
            }

            // 检查参数类型
            for(Map.Entry<String,ToolDefinitionParameter> paramEntry : function.getParameters().getProperties().entrySet()){

                if (params.has(paramEntry.getKey())) {
                    JsonNode value = params.get(paramEntry.getKey());
                    if (!isValidType(value, paramEntry.getValue().getType())) {
                        log.error("Invalid type for parameter: {}", paramEntry.getKey());
                        return false;
                    }
                }
            }

            return true;
        } catch (Exception e) {
            log.error("Error validating input parameters", e);
            return false;
        }
    }

    /**
     * 检查参数类型是否有效
     */
    private boolean isValidType(JsonNode value, String type) {
        switch (type) {
            case "string":
                return value.isTextual();
            case "number":
                return value.isNumber();
            case "boolean":
                return value.isBoolean();
            case "object":
                return value.isObject();
            case "array":
                return value.isArray();
            default:
                return false;
        }
    }
}